package com.shop.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shop.constant.Constants;
import com.shop.entity.LookCartVO;
import com.shop.entity.PayMessage;
import com.shop.exception.DAOException;
import com.shop.factory.ObjectFactory;
import com.shop.service.ShoppingService;
import com.shop.service.UserService;
import com.shop.service.impl.ShoppingServiceImpl;
import com.shop.util.GetMap;
import com.shop.util.PrintJson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import static com.alipay.api.AlipayConstants.CHARSET;

/**
 * <p>Title: ${file_name}</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2020</p>
 * <p>Company: www.baidudu.com</p>
 *
 * 410 系统正在维护中
 * 411 用户不存在
 * 412 用户已存在
 * 413 用户信息修改失败
 *
 * @author andy
 * @version 1.0
 * @date ${date}
 */

@WebServlet("/u_shopping/*")
public class ShoppingController extends HttpServlet {

    private final String APP_ID = "2021000118642793";
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDFAmUpN3YmYnUtNZg7PmkeT6oWabfhZZeJ69NpamovnJ7g/f9I7aLEaOcCOlC09fLEB715JfCTsvjnRa0EQY4Y+mKDSZcCdTJqQrAIAJ8PXbre+D6PRHVT2A2h0xMqr0OMnD+NZCv/7cTChNVtEtlKQP4CC7xEoItZPk2st9gil/t62yqZHYOOGk9Cdp2bwdDY96hqqXIg8YscJLWcWjo04HQW2koA/5CrJbwm1athaVGmbFkT/FbEJA411K4stj2B/qvhCwBJ2pcG8knrYGZz1f0ONR1jh42EfCD0Kt1Nu0UVP5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2Dlv7CKQKBgCRAO3DsEwowWFV/p//kMsiM9nrh2k0wAvjyEvQkjTqcdxyIoOQ7BGWgaOL4TFq7DeoAhWAPpvE3hJ+GNIMl8qdp1aCWxLehS5Or0hNF4+fW0RaxSAssXkQ7Gfgz61iZsKcdHDFI0GqYv3NtljD//9iYrML2SFyDafxrnwkDxMfo";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0MNsCyNGxFivPkKWsvI3+IErZxYtsjuixCv5dYtH05uYCHeB1NwHfHGuVgcHSJh+8Fni5GEGEmViBoRFlJjnVpDHwHWKapI0Pm0z2YQHIWii2nKqqnqvSSGVCRJyGIyilvyySd3IWDLKv7r65Bniq8+YAKTyo+UpMeuRUvSgfqEb5M5RMqvNh0H+iDMbaGYtpj4Wb1A+u4JLf9X1XorkFNOXm4LeWELrxGHt7D7eqgWL1vOV7xz4XMYf+g9QJ5wWDcoeG8HwwykO9tra1sRMWUU0Y+qnRgS18Olf0Nu/ITCG4pnFljRD62BgRJa21nlBZT6jmffRKEJEB0lzFuo9kwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    //private final String NOTIFY_URL = "http://192.168.1.140:8081/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8088/shop/u_shopping/pay_success";

    private ShoppingService shoppingService = (ShoppingServiceImpl) ObjectFactory.getInstance(Constants.SHOPPING_SERVICE_KEY);

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        if("/shop/u_shopping/submit/order".equals(uri)) {
            submitOrder(req,resp);
        } else if("/shop/u_shopping/prepare_pay".equals(uri)) {
            preparePay(req,resp);
        } else if("/shop/u_shopping/pay".equals(uri)) {
            pay(req,resp);
        }else if("/shop/u_shopping/pay_success".equals(uri)) {
            paySuccess(req,resp);
        }else if("/shop/u_shopping/BuyNow".equals(uri)){
            BuyNow(req,resp);
        }
    }

    //支付成功
    private void paySuccess(HttpServletRequest req, HttpServletResponse resp) {
        String o_id = req.getParameter("o_id");

        Map<String, Object> map = null;
        try {
            shoppingService.changecPayState(o_id);
            map = GetMap.getMap(200, "支付成功");
            resp.sendRedirect("/shop/PaySucces.html");
        } catch (DAOException | IOException e) {
            map = GetMap.getMap(410, "支付失败");
            e.printStackTrace();
        }
//        catch (IOException e) {
//            e.printStackTrace();
//        }
        PrintJson.printJsonObj(resp,map);
    }

    private void preparePay(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取订单号
        String id = req.getParameter("o_id");
        int o_id = Integer.parseInt(id);

        PayMessage pm = null;
        try {
            pm = shoppingService.getPayMessage(o_id);
            req.setAttribute("pm",pm);
            req.getRequestDispatcher("/u_shopping/pay").forward(req, resp);
        } catch (DAOException e) {
            e.printStackTrace();
        }
    }

    private void pay(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //获取req作用域中的pm信息
        PayMessage pm = (PayMessage) req.getAttribute("pm");
        //在公共参数中设置回跳和通知地址
        String url = RETURN_URL + "?o_id=" + pm.getO_id();
        request.setReturnUrl(url);
        //request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        int out_trade_no = pm.getO_id();
        //付款金额，必填
        double total_amount =pm.getO_total();
        //商品名称和描述信息
//        String[] names = pm.getG_names();
//        String[] datas = pm.getG_datas();
        //商品名称，必填
        String subject ="尊敬的会员,欢迎购买";
        //商品描述，可空
        String body = "尊敬的会员,欢迎购买";

        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        resp.setContentType("text/html;charset=" + CHARSET);
        resp.getWriter().write(form);// 直接将完整的表单html输出到页面
        resp.getWriter().flush();
        resp.getWriter().close();
    }

    private void submitOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("u_id");
        int u_id = Integer.parseInt(id);
        String total = req.getParameter("o_total");
        double o_total = Double.parseDouble(total);
        JSONObject json = PrintJson.paraseJson(req);
        JSONArray gd_id = json.getJSONArray("gd_id");
        JSONArray s_id = json.getJSONArray("s_id");

        int o_id = 0;
        Map<String, Object> map = null;
        try {
            //提交订单,返回订单id
            o_id = shoppingService.order(u_id,o_total,gd_id,s_id);
            map = GetMap.getMap(200, "订单提交成功");
            map.put("data",o_id);
            map.put("href","/api/u_shopping/prepare_pay?o_id="+o_id);
        } catch (DAOException e) {
            map = GetMap.getMap(410, e.getMessage());
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
        //resp.sendRedirect("/api/u_shopping/prepare_pay?o_id="+o_id);
    }
    private void BuyNow(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("u_id");
        int u_id = Integer.parseInt(id);
        String total = req.getParameter("o_total");
        double o_total = Double.parseDouble(total);
        JSONObject json = PrintJson.paraseJson(req);
        String gd_id = req.getParameter("gd_id");
        String s_id = req.getParameter("s_id");

        int o_id = 0;
        Map<String, Object> map = null;
        try {
            //提交订单,返回订单id
            o_id = shoppingService.BuyNow(u_id,o_total,gd_id,s_id);
            map = GetMap.getMap(200, "订单提交成功");
            map.put("data",o_id);
            map.put("href","/api/u_shopping/prepare_pay?o_id="+o_id);
        } catch (DAOException e) {
            map = GetMap.getMap(410, e.getMessage());
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        PrintJson.printJsonObj(resp,map);
        //resp.sendRedirect("/api/u_shopping/prepare_pay?o_id="+o_id);
    }
}
